import { Feature } from 'ol'
import VectorSource from 'ol/source/Vector'
import VectorLayer from 'ol/layer/Vector'
import { Stroke, Style, Fill } from 'ol/style'
import CircleStyle from 'ol/style/Circle'
import { Draw } from 'ol/interaction'
import { getArea, getLength } from 'ol/sphere'
import { unByKey } from 'ol/Observable'
import { Overlay } from 'ol'
import { LineString, Polygon } from 'ol/geom'
import { transform, fromLonLat } from 'ol/proj'
import { styleList } from '@/utils/style.js'

// turf 用于简单的空间计算
import * as turf from '@turf/turf'

var _map = null
var mapMouseMove = null
var helpTooltip = null
var helpTooltipElement = null
var feature = null
var draw = null
var listener = null
var measureTooltipElement = null
var measureTooltip = null
var drawLayers = []
var drawElements = []

cpRPA.setDistanceFn(distance)
cpRPA.setLatlng2PxFn(latlng2Px)
cpRPA.setPx2LatlngFn(px2Latlng)

function distance(p1, p2) {
  const point1 = turf.point([parseFloat(p1.lng), parseFloat(p1.lat)])
  const point2 = turf.point([parseFloat(p2.lng), parseFloat(p2.lat)])
  return turf.distance(point1, point2, { units: 'meters' })
}

function latlng2Px(latlng) {
  const pixel = _map.getPixelFromCoordinate(fromLonLat([latlng.lng, latlng.lat]))
  return {
    x: pixel[0],
    y: pixel[1]
  }
}

function px2Latlng(px) {
  const coord = transform(
    _map.getCoordinateFromPixel(px),
    'EPSG:3857',
    'EPSG:4326'
  )
  return {
    lat: coord[1],
    lng: coord[0]
  }
}

/**
     *  测距
     */
export function measure(map, measureType) {
  _map = map
  // 创建一个数据源,用于放置绘制过程中和绘制结束后的线段
  const source = new VectorSource()
  // 添加图层，用来放置数据源
  const layer = new VectorLayer({
    source: source,
    style: new Style({
      fill: new Fill({
        color: 'rgba(255, 255, 255, 0.2)'
      }),
      stroke: new Stroke({
        color: '#ffcc33',
        width: 4
      }),
      image: new CircleStyle({
        radius: 7,
        fill: new Fill({
          color: '#ffcc33'
        })
      })
    })
  })

  mapMouseMove = _map.on('pointermove', (evt) => {
    if (evt.dragging) {
      return
    }
    let helpMsg = '单击开始测量'
    if (feature) {
      helpMsg = '双击结束测量'
    }
    helpTooltipElement.innerHTML = helpMsg
    helpTooltip.setPosition(evt.coordinate)
    helpTooltipElement.classList.remove('hidden')
  })

  _map.getViewport().addEventListener('mouseout', () => {
    helpTooltipElement.classList.add('hidden')
  })

  draw = new Draw({
    source,
    // 测量方式 polygon 或者 lineString
    type: measureType,
    style: new Style({
      fill: new Fill({
        color: 'rgba(255, 255, 255, 0.2)'
      }),
      stroke: new Stroke({
        color: 'rgba(0, 0, 0, 0.5)',
        lineDash: [10, 10],
        width: 4
      }),
      image: new CircleStyle({
        radius: 5,
        stroke: new Stroke({
          color: 'rgba(0, 0, 0, 0.7)'
        }),
        fill: new Fill({
          color: 'rgba(255, 255, 255, 0.2)'
        })
      })
    })
  })

  // 开始进行绘制
  draw.on('drawstart', (evt) => {
    feature = evt.feature
    let tooltipCoord = evt.coordinate
    listener = feature.getGeometry().on('change', (evt) => {
      const geom = evt.target
      //   let output
      if (geom instanceof Polygon) {
        // output = formatArea(geom)
        tooltipCoord = geom.getInteriorPoint().getCoordinates()
      } else if (geom instanceof LineString) {
        // output = formatLength(geom)
        tooltipCoord = geom.getLastCoordinate()
      }

      //   data.measureTooltipElement.innerHTML = output
      measureTooltip.setPosition(tooltipCoord)
    })
  })

  // 绘制完成
  draw.on('drawend', (evt) => {
    measureTooltipElement.className = 'ol-tooltip ol-tooltip-static'
    measureTooltip.setOffset([0, -7])
    feature = null
    measureTooltipElement = null
    // createMeasureTooltip()
    map.removeInteraction(draw)
    draw = null
    unByKey(listener)
    listener = null
    unByKey(mapMouseMove)
    mapMouseMove = null

    var feature = evt.feature
    var geometry = feature.getGeometry()
    var coordinate = geometry.getCoordinates()
    if (geometry instanceof LineString) {
      console.log(coordinate)
    } else if (geometry instanceof Polygon) {
    //   const lngLats = []
    //   const len = coordinate[0].length
    //   for (let i = 0; i < len - 1; i++) {
    //     const coord = transform(
    //       coordinate[0][i],
    //       'EPSG:3857',
    //       'EPSG:4326'
    //     )
    //     lngLats.push(
    //       {
    //         lat: coord[1],
    //         lng: coord[0]
    //       }
    //     )
    //   }

      //   var polyline = cpRPA.setOptions({
      //     polygon: lngLats,
      //     rotate: 0,
      //     space: 20
      //   })

    //   drawPolyline(formatPolyline(polyline))
    }
  })

  createHelpTooltip()
  createMeasureTooltip()
  _map.addLayer(layer)
  drawLayers.push(layer)
  _map.addInteraction(draw)
}

// 计算长度
const formatLength = (line) => {
  // ol自带的计算线段长度方法
  const length = getLength(line)
  let output
  // 长度大于100米单位为km, 否则为m
  if (length > 100) {
    output = Math.round((length / 1000) * 100) / 100 + ' ' + 'km'
  } else {
    output = Math.round(length * 100) / 100 + ' ' + 'm'
  }
  return output
}

// 计算面积
const formatArea = (polygon) => {
  const proj = _map.getView().getProjection()
  const area = getArea(polygon, { projection: proj })
  let output
  if (area > 10000) {
    output = Math.round((area / 1000000 * 100) / 100) + ' ' + 'km<sup>2</sup>'
  } else {
    output = Math.round(area * 100) / 100 + ' ' + 'm<sup>2</sup>'
  }
  return output
}

const createMeasureTooltip = () => {
  if (measureTooltipElement) {
    measureTooltipElement.parentNode.removeChild(measureTooltipElement)
  }
  measureTooltipElement = document.createElement('div')
  measureTooltipElement.className = 'ol-tooltip ol-tooltip-measure'
  measureTooltip = new Overlay({
    element: measureTooltipElement,
    offset: [0, -15],
    positioning: 'bottom-center',
    stopEvent: false,
    insertFirst: false
  })
  drawElements.push(measureTooltip)
  _map.addOverlay(measureTooltip)
}

const createHelpTooltip = () => {
  if (helpTooltipElement) {
    helpTooltipElement.parentNode.removeChild(helpTooltipElement)
  }
  helpTooltipElement = document.createElement('div')
  helpTooltipElement.className = 'ol-tooltip hidden'
  helpTooltip = new Overlay({
    element: helpTooltipElement,
    offset: [15, 0],
    positioning: 'center-left'
  })
  _map.addOverlay(helpTooltip)
}
